import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { useMessage } from 'naive-ui'
import { secureStorage } from '@/utils/secureStorage'
const request: AxiosInstance = axios.create({
  baseURL: '/api', //
  timeout: 10000, //
  headers: {
    // 'Content-Type': 'application/json',
  },
})
request.interceptors.request.use(
    (config: any) => {
        const token = secureStorage.get("token"); // 获取token
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    (error) => {
        // Handle request error here
        return Promise.reject(error);
    }
);

// Response interceptor
request.interceptors.response.use(
    (response: AxiosResponse) => {
        // Handle response data here
        return response.data;
    },
    (error) => {
        // Handle response error he
        let msg = "";
        let status = error.response.status;
        switch (status) {
            case 401:
                msg = "token过期";
                break;
            case 403:
                msg = "无权访问";
                break;
            case 404:
                msg = "请求地址错误";
                break;
            case 500:
                msg = "服务器出现问题";
                break;
            default:
                msg = "无网络";
                return Promise.reject(error);
        }
        useMessage().error(msg);
    }
);

export default request;